﻿
package com.thinkgem.jeesite.modules.KDniao.service.meRequest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkgem.jeesite.modules.KDniao.entity.LogisticTrackingTrajectory;
import com.thinkgem.jeesite.modules.KDniao.entity.LogisticsThreeParty;
import com.thinkgem.jeesite.modules.KDniao.entity.requestKDniao.requestKDniaoData;
import com.thinkgem.jeesite.modules.KDniao.entity.requestKDniao.responseKDniaoResult;
import com.thinkgem.jeesite.modules.KDniao.service.logistics.LogisticTrackingTrajectoryService;
import com.thinkgem.jeesite.modules.KDniao.service.logistics.LogisticsThreePartyService;
import com.thinkgem.jeesite.modules.KDniao.unit.CacheUtils;
import com.thinkgem.jeesite.modules.KDniao.unit.KDnaioUnit;

/**
*
* 快递鸟订阅推送2.0接口
* @see: http://www.kdniao.com/api-subscribe
* @copyright: 深圳市快金数据技术服务有限公司
* 
* ID和Key请到官网申请：http://www.kdniao.com/ServiceApply.aspx
*/

@Service
public class KdniaoSubscribeAPI {
    private static Logger logger = LoggerFactory.getLogger(KdniaoSubscribeAPI.class);
    @Autowired
    private KDnaioUnit kDnaioUnit;

    @Autowired
    private LogisticsThreePartyService logisticsThreePartyService;

    @Autowired
    private LogisticTrackingTrajectoryService logisticTrackingTrajectoryService;
    /***
     * Json方式 物流信息订阅
     * 
     * @param ShipperCode
     *            快递公司编号
     * @param OrderCode订单号
     * @param LogisticCode物流单号
     * @return
     * @throws Exception
     */
    public responseKDniaoResult orderTracesSubByJson(String ShipperCode, String OrderCode, String LogisticCode) throws Exception {
        LogisticTrackingTrajectory logisticTrackingTrajectory = logisticTrackingTrajectoryService
                .getTrackingTrajectorybyOrderCode(OrderCode);
        //排除是否重复订阅
        logger.info(OrderCode);
        if (logisticTrackingTrajectory != null && !"".equals(logisticTrackingTrajectory.getId())) {
            if (logisticTrackingTrajectory.getShippercode().equals(ShipperCode)) {
                if (logisticTrackingTrajectory.getLogisticcode().equals(LogisticCode)) {
                    return null;
                }
            }
        }
        LogisticsThreeParty lk = getLogisticsThreeParty();
        requestKDniaoData data = new requestKDniaoData();
        data.setOrderCode(OrderCode);
        data.setShipperCode(ShipperCode);
        data.setLogisticCode(LogisticCode);
        data.setCallBack(OrderCode);
        ObjectMapper mapper = new ObjectMapper();
        String requestData = mapper.writeValueAsString(data);
		Map<String, String> params = new HashMap<String, String>();
        params.put("RequestData", kDnaioUnit.urlEncoder(requestData, "UTF-8"));
        params.put("EBusinessID", lk.getEbusinessid());
		params.put("RequestType", "1008");
        String dataSign = kDnaioUnit.encrypt(requestData, lk.getAppkey(), "UTF-8");
        params.put("DataSign", kDnaioUnit.urlEncoder(dataSign, "UTF-8"));
		params.put("DataType", "2");
		
        String result = kDnaioUnit.sendPost(lk.getRequestUrl(), params);
        logger.info(result);
        if (result == null || "".equals(result)) {
            return null;
        }
		//根据公司业务处理返回的信息......
        responseKDniaoResult responseResult = mapper.readValue(result, responseKDniaoResult.class);
        if (responseResult.isSuccess()) {
            if (logisticTrackingTrajectory != null && !"".equals(logisticTrackingTrajectory.getId())) {
                //修改订单物流信息
                savaLogisticTrackingTrajectory(responseResult, ShipperCode, OrderCode, LogisticCode, logisticTrackingTrajectory);
            } else
                //新建
                savaLogisticTrackingTrajectory(responseResult, ShipperCode, OrderCode, LogisticCode, null);
        }
        return responseResult;
	}
		
    @SuppressWarnings("unchecked")
    public LogisticsThreeParty getLogisticsThreeParty() {
        List<LogisticsThreeParty> lks = (List<LogisticsThreeParty>) CacheUtils.get("LogisticsThreePartyisenadleList");
        logger.info("快递鸟配置" + lks);
        if (lks == null || lks.isEmpty() || lks.size() == 0) {
            lks = logisticsThreePartyService.findisenadleList();
            CacheUtils.put("LogisticsThreePartyisenadleList", lks);
            logger.info("快递鸟配置" + lks);
        }
        if (lks.size() == 0)
            return null;
        else
            return lks.get(0);
    }

    public synchronized void savaLogisticTrackingTrajectory(responseKDniaoResult responseResult, String ShipperCode, String OrderCode,
            String LogisticCode, LogisticTrackingTrajectory logisticTrackingTrajectory) {
        logger.info("保存订阅信息");
        if (responseResult.isSuccess()) {
            if(logisticTrackingTrajectory==null)
                logisticTrackingTrajectory = new LogisticTrackingTrajectory();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            
            logisticTrackingTrajectory.setOrdercode(OrderCode);
            logisticTrackingTrajectory.setLogisticcode(LogisticCode);
            logisticTrackingTrajectory.setShippercode(ShipperCode);
            logisticTrackingTrajectory.setCreatetime(new Date());
            logisticTrackingTrajectory.setSuccess("true");
            logisticTrackingTrajectory.setDatas(null);
            if (responseResult.getEstimatedDeliveryTime() != null && !"".equals(responseResult.getEstimatedDeliveryTime())) {
                try {
                    logisticTrackingTrajectory.setEstimateddeliverytime(formatter.parse(responseResult.getEstimatedDeliveryTime()));
                } catch (ParseException e) {
                    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        logisticTrackingTrajectory.setEstimateddeliverytime(formatter2.parse(responseResult.getEstimatedDeliveryTime()));
                    } catch (ParseException e1) {
                        logger.info("时间格式化有问题");
                    }

                }
            }
            logisticTrackingTrajectoryService.save(logisticTrackingTrajectory);
            logger.info("保存成功！");
        }
    }
}
